/**
 * @file     numIslands.js
 * @brief    [200. 岛屿数量](https://leetcode.cn/problems/number-of-islands/)
 * @author   Zhu
 * @date     2024-11-29 17:37
 */

/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function (grid) {
    function matrix(n, m) {
        return Array(n)
            .fill(0)
            .map((_) => Array(m).fill(0));
    }

    const n = grid.length;
    const m = grid[0].length;
    const visited = matrix(n, m);
    let count = 0;

    function visit(i, j) {
        if (i < 0 || j < 0 || i >= n || j >= m) return -1; // 越界，返回值不取
        if (visited[i][j]) return 0; // counted
        const item = grid[i][j];
        if (item == '1') {
            visited[i][j] = 1;
            visit(i + 1, j); // -->
            visit(i, j + 1); // ↓
            visit(i, j - 1); // <--
            visit(i - 1, j); // ↑
            return 1;
        }
        visited[i][j] = 0;
        return 0;
    }

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            count += visit(i, j);
        }
    }

    return count;
};
